// index.js
import {
  getGoodsList,
  getSwiperList,
} from '../../network/index.js';
// 获取应用实例
const {
  globalData
} = getApp()

Page({
  data: {
    url_pre: globalData.BASE_URL,
    swiper: [],
    goodsList: [],
    total: 0,
    page: 1,
    pageSize: 10,
    isOK: false,
    valueText: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  // 页面加载
  onLoad() {
    // 业务请求开始 模拟进入页面即发起请求
    this.init();
  },
  init() {
    this.setData({
      goodsList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      isOK: false,
    });
    this.getGoodsList();

    this.getSwiperList();
  },
  // 获取轮播数据
  getSwiperList() {
    getSwiperList().then((result) => {
      this.setData({
        swiper: result
      })
    })
  },

  async getGoodsList() {
    wx.showLoading({
      title: '加载中',
    })
    await getGoodsList({
      page: this.data.page,
      pageSize: this.data.pageSize
    }).then((result) => {
      const {
        items,
        total
      } = result;
      const data = items.map(item => {
        item.url = this.data.url_pre + item.urls?.split(",")[0] || "default.png";
        console.log(item.label)
        item.labels = item.label ? item.label?.split(",") : [];
        return item;
      })
      console.log(data)
      const goodsList = [...this.data.goodsList, ...data];
      this.setData({
        total,
        page: this.data.page++,
        goodsList
      })
    })
    if (this.data.total <= this.data.goodsList.length) {
      this.setData({
        isOK: true
      });
    }
    wx.hideLoading();
  },
  clickInput() {
    wx.navigateTo({
      url: `/pages/search/search`
    })
  },

  navigateTo(event) {
    const {
      userInfo
    } = getApp().globalData;
    if (!userInfo.nickName) {
      wx.showModal({
        title: '提示',
        content: '使用该功能请先登录',
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/me/me'
            })
          }
        }
      })
      return;
    }
    const {
      id
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/goodsDetails/goodsDetails?id=${id}`
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isOK) {
      return;
    }
    this.getGoodsList();
  },
})